package Socket03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务端
 */
public class Server {
    private ServerSocket serverSocket;
    private int index;
    private List<PrintWriter> list;

    public Server(){
        list = new ArrayList<>();
        try {
            serverSocket = new ServerSocket(100);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接客户端
     */
    public void start(){
        while(true){
            try {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("客户端"+(++index)+"已连接");

                Thread t = new Thread(new ServerHandler(socket));
                t.start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接受发送数据
     */
    private class ServerHandler implements Runnable{
        private Socket socket;
        private String name;


        public ServerHandler(Socket socket){
            this.socket = socket;
            name = socket.getInetAddress().getHostName();
        }
        @Override
        public void run() {
            PrintWriter pw =null;
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));
                pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream())),true);

                synchronized (list){
                    list.add(pw);
                }

                String s;
                while ((s = br.readLine()) != null){
                    synchronized (list){
                        for (PrintWriter p : list) {
                            System.out.println(name+"说："+s);
                            p.println(s);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                synchronized (list){
                    list.remove(pw);
                }
                System.out.println(name+"下线了，当前在线人数"+list.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 主方法
     * @param args
     */
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
